﻿using System;
using MyLib.Web.UI;

namespace MyLib.Web.Pages {
	/// <summary>
	/// 
	/// </summary>
	public abstract class MyAccountPage : MyPage {
		/// <summary>
		/// 
		/// </summary>
		private const int DefaultApplicationId = 1;

		/// <summary>
		/// 
		/// </summary>
		protected int ApplicationId {
			get {
				var obj = ViewState["ApplicationId"];
				if (obj == null) {
					return DefaultApplicationId;
				} else {
					return (int)obj;
				}
			}
			set {
				ViewState["ApplicationId"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		protected void DoQueryOne() {
			var formView1 = this.FindDescendantControl<MyFormView>("FormView1");
			formView1.DataBind();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected string EvalGroupName() {
			var row = (System.Data.DataRowView)Page.GetDataItem();

			var grpId = row["grpId"];

			return Context.GetCodeTextFromValue("SysCode.xml", 40, grpId);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected string EvalStatusText() {
			var row = (System.Data.DataRowView)Page.GetDataItem();

			var status = row.Get<int>("status");

			return status == 1 ? Properties.Main.Enabled : Properties.Main.Disabled;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			// Add object datasources.
			var ds1 = new MyObjectDataSource(typeof(MyLib.Data.AuthorityProvider).AssemblyQualifiedName, "FindUserById");
			ds1.ID = "ObjectDataSource1";
			ds1.EnableCaching = false;
			ds1.EnablePaging = false;

			ds1.SelectParameters.Add("applicationId", System.Data.DbType.Int32, ApplicationId.ToString());
			ds1.SelectParameters.Add(new MyUserParameter {
				Name = "userId",
				Type = TypeCode.String
			});

			Controls.Add(ds1);

			// Assign event handlers.

			var formView1 = this.FindDescendantControl<MyFormView>("FormView1");
			formView1.DataSourceID = ds1.ID;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.Title = Properties.Main.TitleMyAccount;

			if (!IsPostBack) {
				Context.ExecuteSafely(DoQueryOne);
			}
		}
	} // end of MyAccountPage.
}
